#ifndef IMPLEMENT_H
#define IMPLEMENT_H
#include"head.h"
#include<queue>


graph::graph(){
    v=new vertex[5];
    ehead=NULL;
    mark=new int[5];
    for(int i=0;i<5;i++){
        mark[i]=0;
    }
}

graph::~graph(){
    adjList *cur,*nex;
    int i;
    edge *curE=ehead;
    for(i=0;i<5;i++){
        cur=v[i].adj;
        while(nex!=NULL){
            cur=nex;
            nex=nex->next;
            delete cur;
        }
    }
    while(ehead!=NULL){
        curE=ehead;
        ehead=ehead->next;
        delete curE;
    }
    delete [] v;
    delete [] mark;
}


void graph::setEdge(int st,int en,int w){
    edge *cur;
    cur=ehead->next;
    adjList *curAL,*p;
    curAL=v[st].adj;
//    v[st].adj=new adjList;
//    v[st].adj->e(st,en,w);
//    v[st].adj->next=curAL;
//    v[st].adj->nextVertex=en;
    while(curAL!=NULL){
         if(curAL->nextVertex<en)
             curAL=curAL->next;
         else break;
    }
    p=curAL;
    curAL=new adjList;
//    curAL->e(st,en,w);
    curAL->e.start=st;
    curAL->e.end=en;
    curAL->e.weight=w;

    curAL->nextVertex=en;
    curAL->next=p;

    ehead->next=new edge;
//    ehead->next->i=edgeNum;
    ehead->next=&(v[st].adj->e);
    ehead->next->next=cur;
    edgeNum++;

}


void graph::showBfs(){
    for(int i=0;i<5;i++)
        mark[i]=0;
    cout<<endl;
    for(int i=0;i<5;i++){
        if(!mark[i])
            Bfs(i);
    }
}
void graph::Bfs(int i){
    mark[i]=1;
    queue<int> q;
    cout<<v[i].i<<"  ";
    q.push(i);

    while(v[i].adj!=NULL){
        i=q.front();
        q.pop();
        for(int eg=FirstEdge(i);eg>0;eg=NextEdge(i,eg)){
            if(eg!=-1&&!mark[eg]){
                cout<<v[eg].i<<"  ";
                mark[eg]=1;
                q.push(eg);
            }
        }
    }
}
int graph::FirstEdge(int i){
    if(v[i].adj!=NULL){
        return v[i].adj->nextVertex;}
    else return -1;
}
int graph::NextEdge(int i,int eg){
    adjList *cur=v[i].adj;
    while(cur->nextVertex!=eg){
        cur=cur->next;
    }
    if(cur)
        return cur->next->nextVertex;
    return -1;
}


#endif // IMPLEMENT_H
